package com.example.common.config.sentinel;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSONObject;
import com.example.common.constant.BizCodeEnum;
import com.example.common.utils.R;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 公共 sentinel 配置
 */
@Configuration
public class SecKillSentinelConfig {

    public SecKillSentinelConfig() {
        WebCallbackManager.setUrlBlockHandler(
                new UrlBlockHandler() {
                    @Override
                    public void blocked(HttpServletRequest req,
                                        HttpServletResponse resp,
                                        BlockException e) throws IOException {
                        R error = R.error(BizCodeEnum.TO_MANY_REQUEST.getCode(), BizCodeEnum.TO_MANY_REQUEST.getMsg());
                        resp.setCharacterEncoding("UTF-8");
                        resp.setContentType("application/json;charset=utf8");
                        resp.getWriter().write(JSONObject.toJSONString(error));
                    }
                }
        );
    }
}
